package com.echat.ebluetooth.protocol;

import android.util.Log;

import com.echat.ebluetooth.util.BitOperator;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UDPClient {

    private static final String TAG = "UdpClient";
    private static UDPClient instance;

    private DatagramSocket mSocket;
    private ExecutorService mExecutor;

    public static UDPClient getInstance(){
        if(instance == null){
            instance = new UDPClient();
        }
        return instance;
    }

    private UDPClient() {
        create();
    }

    private void create() {
        try {
            mExecutor = Executors.newSingleThreadExecutor();
            mSocket = new DatagramSocket();
            mSocket.setSoTimeout(3000);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public void send(final String host, final int port, final byte[] data){
        Log.i(TAG, host + ":" + port + "数据：" + BitOperator.bytesToHex(data).replaceAll("(.{2})", "$1 "));
        mExecutor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(host), port);
                    mSocket.send(packet);
                } catch (IOException e) {
                    Log.i(TAG, "run: 发送失败");
                    e.printStackTrace();
                }
            }
        });
    }

    public void close(){
        if(mSocket != null){
            mSocket.close();
        }
        if(mExecutor != null){
            mExecutor.shutdown();
        }
    }
}
